<template>
	<el-dialog width="99%" :close-on-click-modal="false" v-model="dialogVisible" :title="state.title" destroy-on-close :before-close="handleClose">
		<el-form ref="qualInspecRef" :model="state.form">
			<el-table
				ref="dataTableRef"
				row-key="id"
				:tree-props="{ children: 'itemList' }"
				:span-method="arraySpanMethod"
				min-height="50vh"
				:header-cell-style="{ color: '#000' }"
				:row-class-name="tableRowClassName"
				:default-expand-all="true"
				border
				:data="state.form.infoData"
			>
				<!-- <el-table-column label="" width="30px" fixed="left" /> -->
				<el-table-column label="备货平台" prop="companyName" min-width="120px">
					<template v-slot="scope">
						<el-descriptions v-if="scope.row.itemList" :column="4">
							<el-descriptions-item>
								{{ scope.row.inboundOrderCode }}
							</el-descriptions-item>
							<el-descriptions-item label="收获仓：">
								{{ scope.row.whNameTo }}
							</el-descriptions-item>
							<el-descriptions-item label="公司主体：">
								{{ scope.row.companyName }}
							</el-descriptions-item>
							<el-descriptions-item label="团队：">
								{{ scope.row.teamName }}
							</el-descriptions-item>
							<el-descriptions-item label="备货区域">
								{{ scope.row.stockupAreaName }}
							</el-descriptions-item>
							<el-descriptions-item label="业务类型：">
								<span v-for="item in inbound_bus_type" :key="item.id" v-show="Number(item.value) === Number(scope.row.busType)">
									{{ item.label }}
								</span>
							</el-descriptions-item>
						</el-descriptions>
						<span v-else>
							{{ scope.row.stockupPlatformName }}
						</span>
					</template>
				</el-table-column>
				<el-table-column label="产品图片" prop="picUrl" min-width="120px">
					<template v-slot="scope">
						<ewt-image :url="scope.row.picUrl" style="width: 36px; height: 36px; object-fit: contain" />
					</template>
				</el-table-column>
				<el-table-column label="产品名称/SKU" prop="companyName" min-width="160px">
					<template v-slot="scope">
						{{ scope.row.skuName || '-' }}<br /><br />
						{{ scope.row.skuCode || '-' }}
					</template>
				</el-table-column>
				<el-table-column label="MSKU/FNSKU" prop="companyName" min-width="120px">
					<template v-slot="scope">
						{{ scope.row.mskuCode || '-' }}<br /><br />
						{{ scope.row.fnsku || '-' }}
					</template></el-table-column
				>
				<el-table-column label="应收数量" prop="supposeReceiveQty" min-width="120px"></el-table-column>
				<el-table-column label="实收数量" prop="receivedQtyTotal" min-width="120px"> </el-table-column>
				<el-table-column label="良品量" prop="goodQty" min-width="140px">
					<template #header>
						<span class="table-require">良品量</span>
						<el-text type="primary" style="cursor: pointer" @click="toInputQty">一键填入</el-text>
					</template>
					<template v-slot="scope">
						<el-form-item label="" :prop="'infoData.' + getPropPosi(scope.row) + '.goodQty'" :rules="state.rules.goodQty">
							<el-input
								v-model="scope.row.goodQty"
								oninput="value=value.replace(/^\D*(\d{0,9}(?:)?).*$/g,'$1')"
								@blur="
									scope.row.goodQty = Number($event.target.value);
									judgeSum(scope.row);
								"
							></el-input>
						</el-form-item>
					</template>
				</el-table-column>
				<el-table-column label="次品量" prop="defectiveQty" min-width="100px">
					<template #header>
						<span class="table-require">次品量</span>
					</template>
					<template v-slot="scope">
						<el-form-item label="" :prop="'infoData.' + getPropPosi(scope.row) + '.defectiveQty'" :rules="state.rules.defectiveQty">
							<el-input
								v-model="scope.row.defectiveQty"
								oninput="value=value.replace(/^\D*(\d{0,9}(?:)?).*$/g,'$1')"
								@blur="
									scope.row.defectiveQty = Number($event.target.value);
									judgeSum(scope.row);
								"
							></el-input>
						</el-form-item>
					</template>
				</el-table-column>
				<el-table-column label="废品量" prop="scrapQty" min-width="100px">
					<template #header>
						<span class="table-require">废品量</span>
					</template>
					<template v-slot="scope">
						<el-form-item label="" :prop="'infoData.' + getPropPosi(scope.row) + '.scrapQty'" :rules="state.rules.scrapQty">
							<el-input
								v-model="scope.row.scrapQty"
								oninput="value=value.replace(/^\D*(\d{0,9}(?:)?).*$/g,'$1')"
								@blur="
									scope.row.scrapQty = Number($event.target.value);
									judgeSum(scope.row);
								"
							></el-input>
						</el-form-item>
					</template>
				</el-table-column>
			</el-table>
		</el-form>

		<template #footer>
			<el-button type="" @click="handleClose">取消</el-button>
			<el-button type="primary" class="ml10" @click="toSaveReceive">完成收货</el-button>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup  name="qualInspecDialog">
import { ElMessage } from 'element-plus';
import { useDict } from '/@/hooks/dict';
const { inbound_bus_type } = useDict('inbound_bus_type');
import { completeInspection } from '../api.ts';
const state = reactive({
	title: '质检',
	form: {
		infoData: [],
	},

	rules: {
		goodQty: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		defectiveQty: [{ required: true, message: '', trigger: ['blur', 'change'] }],
		scrapQty: [{ required: true, message: '', trigger: ['blur', 'change'] }],
	},
});
const dialogVisible = ref(false);
const dataTableRef = ref();
const qualInspecRef = ref();
const emit = defineEmits(['refresh']);
const getPropPosi = (row) => {
	let posi = findPosi(state.form.infoData, row, '', '');
	return posi;
};
const findPosi = (list, row, posi, current) => {
	for (let i = 0; i < list.length; i++) {
		if (list[i].id == row.id) {
			return current + i;
		}
		if (list[i].itemList && list[i].itemList?.length) {
			posi = findPosi(list[i].itemList || [], row, posi, i + posi + '.itemList.');
		}
	}
	return posi;
};

// 打开弹窗
const openDialog = async (list) => {
	state.form.infoData = JSON.parse(JSON.stringify(list));
	state.form.infoData.forEach((item) => {
		item.itemList.map((i) => {
			i.goodQty = 0;
			i.defectiveQty = 0;
			i.scrapQty = 0;
		});
	});
	dialogVisible.value = true;
};
// 关闭弹窗
const handleClose = () => {
	dialogVisible.value = false;
};
const tableRowClassName = ({ row, rowIndex }) => {
	if (row.itemList) {
		return 'row-header';
	}
	return '';
};
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
	if (row.itemList) {
		if (columnIndex === 0) {
			return [1, 9];
		} else if (columnIndex > 0 && columnIndex < 9) {
			return [0, 0];
		} else {
			return [1, 1];
		}
	}
};
const judgeSum = (row) => {
	if (row.goodQty && row.defectiveQty && row.scrapQty) {
		let sum = Number(row.goodQty) + Number(row.defectiveQty) + Number(row.scrapQty);
		if (Number(sum) !== Number(row.receivedQtyTotal)) {
			ElMessage({
				message: '良品量+次品量+废品量应等于实收数量',
				type: 'error',
			});
		}
	}
};
const toInputQty = () => {
	state.form.infoData.forEach((item) => {
		item.itemList.map((i) => {
			i.goodQty = i.receivedQtyTotal;
			i.defectiveQty = 0;
			i.scrapQty = 0;
		});
	});
};
const toSaveReceive = () => {
	qualInspecRef.value.validate((v) => {
		if (v) {
			let msg = null;
			state.form.infoData.forEach((item) => {
				item.itemList.forEach((i) => {
					let sum = Number(i.goodQty) + Number(i.defectiveQty) + Number(i.scrapQty);
					if (Number(sum) !== Number(i.receivedQtyTotal)) {
						msg = '良品量+次品量+废品量应等于实收数量';
					}
				});
			});
			if (msg) {
				ElMessage({
					message: msg,
					type: 'error',
				});
			} else {
				let data = [];
				state.form.infoData.forEach((item) => {
					item.itemList.forEach((i) => {
						let obj = {
							inboundOrderCode: item.inboundOrderCode,
							id: item.id,
							itemId: i.id,
							receivedTotal: i.receivedQtyTotal,
							goodQty: i.goodQty,
							defectiveQty: i.defectiveQty,
							scrapQty: i.scrapQty,
							busId: item.busId,
						};
						data.push(obj);
					});
				});
				completeInspection(data)
					.then((res) => {
						ElMessage({
							message: res.msg || '质检成功',
							type: 'success',
						});
						handleClose();
						emit('refresh');
					})
					.catch((res) => {
						ElMessage({
							message: res.msg,
							type: 'error',
						});
					});
			}
		}
	});
};
defineExpose({
	openDialog,
});
onMounted(() => {});
</script>
<style scoped>
:deep(.el-table .row-header td) {
	background-color: #f5f7fa !important;
}
.table-require::before {
	content: '*';
	color: #e52e2e;
	margin-right: 4px;
}
:deep(.el-table [class*='el-table__row--level'] .el-table__expand-icon) {
	display: none;
}
</style>
